package com.wondersgroup.wuhan_demo.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wondersgroup.wuhan_demo.Constant;
import com.wondersgroup.wuhan_demo.R;
import com.wondersgroup.wuhan_demo.adapter.DeptAdapter;
import com.wondersgroup.wuhan_demo.entity.DaoMaster;
import com.wondersgroup.wuhan_demo.entity.DaoSession;
import com.wondersgroup.wuhan_demo.entity.DeptVo;
import com.wondersgroup.wuhan_demo.util.DBUtil;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class DeptSelectFragment extends Fragment {

    private RecyclerView recyclerView;
    private DeptAdapter adapter;
    private List<DeptVo> deptVos = new ArrayList<>();
    private DBUtil dbUtil;
    private Disposable disposable;
    private static final String SEARCH = "search";
    private String searchKey;

    public static DeptSelectFragment newInstance(String department) {

        Bundle args = new Bundle();
        args.putString(SEARCH, department);
        DeptSelectFragment fragment = new DeptSelectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getContext(), Constant.DB_NAME);
        Database db = helper.getWritableDb();
        DaoSession daoSession = new DaoMaster(db).newSession();
        dbUtil = new DBUtil(daoSession);
        searchKey = getArguments() == null ? "" : getArguments().getString(SEARCH);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_dept_select, container, false);
        recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4, LinearLayoutManager.VERTICAL, false));
        adapter = new DeptAdapter(R.layout.item_dept_select, deptVos);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                getActivity().getSupportFragmentManager().beginTransaction().hide(DeptSelectFragment.this)
                        .add(R.id.content, DoctorSelectFragment.newInstance(
                                deptVos.get(position).getDeptName()
                        )).addToBackStack(null).commit();
            }
        });
        recyclerView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        LaunchActivity launchActivity=(LaunchActivity)getActivity();
        launchActivity.setTopPosition(2);
        searchDepartment(searchKey);
    }

    private void searchDepartment(final String condition) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        Observable.create(new ObservableOnSubscribe<List<DeptVo>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeptVo>> emitter) throws Exception {
                List<DeptVo> list = dbUtil.loadDepartments(condition);
                emitter.onNext(list);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<DeptVo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(List<DeptVo> d) {
                        deptVos.clear();
                        deptVos.addAll(d);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
